<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    *{
      margin: 0;
      padding: 0;
    }
    .box{
      width: 100px;
      height: 100px;
      background-color: pink;
      position: absolute;
    }
    button{
      position: relative;
      top: 120px;
    }
  </style>
</head>
<body>
  <div class="box"></div>
  <button class="start">点击开始</button>
  <button class="stop">点击停止</button>

  <script>
    const box = document.querySelector('.box')
    const start = document.querySelector('.start')
    const stop = document.querySelector('.stop')
    const body = document.body
    let num = 0
    // 计数器
    let timer = null
    // 开始
    start.onclick = function(){
      let speed = 10
      if(timer === null){
        timer = setInterval(() => {
          num += speed
          box.style.left = num + 'px'
          if(num >= body.offsetWidth - box.offsetWidth || num <= 0){
            speed = -speed;
          }
        }, 10)
      }
    }
    // 暂停
    stop.onclick = function(){
      if(timer !== null){
        clearInterval(timer)
        timer = null
      }
    }
  </script>
</body>
</html>